import { JKManager } from "../JKManager"

export type ScreenRotationDirection = `H` | `V`

/**
 * 屏幕旋转控制器
 */
export class ScreenRotationCtrl {
    private _direction: ScreenRotationDirection
    private _canvas: cc.Canvas
    private _designResolution: cc.Size
    private _screenWHRatio: number
    get screenWHRatio() {
        return this._screenWHRatio
    }
    set screenWHRatio(value: number) {
        this._screenWHRatio = value
    }

    /**
     * 初始化
     * @param isPortait 初始屏幕状态是否竖屏，默认竖屏
     */
    init(isPortait: boolean = true) {
        cc.log(`${cc.js.getClassName(this)} init isPortait = ${isPortait}`)

        this._direction = isPortait ? `V` : `H` //H横屏  V竖屏
        this._canvas = cc.Canvas.instance
        this._canvas.fitWidth = isPortait
        this._canvas.fitHeight = !isPortait
        this.screenWHRatio = this._canvas.node.width / this._canvas.node.height
        this._designResolution = this._canvas.designResolution
    }

    // ====================================================================================
    // ===================================== 内部接口 ======================================
    // ====================================================================================

    /**
     * 原生手机旋转监听
     * @param type 屏幕方向类型
     */
    _onOrientationChanged(type: number) {
        cc.log(`${cc.js.getClassName(this)} _onOrientationChanged type = ${type}`)

        if (JKManager.AppConfig.AutoRotateScreen) {
            let frameSize = cc.view.getFrameSize()
            console.log(`frameSize: ` + frameSize.width + `   ` + frameSize.height)

            switch (type) {
                case 0: case 1:
                    //上下
                    if (this._direction === `H` && frameSize.width > frameSize.height) {
                        this._direction = `V`
                        cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT)
                        cc.view.setFrameSize(frameSize.height, frameSize.width)
                        this._canvas.designResolution = cc.size(this._designResolution.width, this._designResolution.height)
                        this._canvas.fitWidth = true
                        this._canvas.fitHeight = false
                    }
                    break
                case 2: case 3:
                    //左右
                    if (this._direction === `V` && frameSize.height > frameSize.width) {
                        this._direction = `H`
                        cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE)
                        cc.view.setFrameSize(frameSize.height, frameSize.width)
                        this._canvas.designResolution = cc.size(this._designResolution.height, this._designResolution.width)
                        this._canvas.fitWidth = false
                        this._canvas.fitHeight = true
                    }
                    break

                default:
                    break
            }
            dispatchEvent(new cc.Event.EventCustom(`resize`, true) as any)
        }
    }

    /**
     * 浏览器进入全屏
     */
    _requestFullscreen() {
        cc.log(`${cc.js.getClassName(this)} _requestFullscreen`)

        if (document.documentElement.requestFullscreen) {
            cc.log(`${cc.js.getClassName(this)} requestFullscreen`)

            document.documentElement.requestFullscreen()
        } else if ((document.documentElement as any).mozRequestFullScreen) {
            cc.log(`${cc.js.getClassName(this)} mozRequestFullScreen`);

            (document.documentElement as any).mozRequestFullScreen()
        } else if ((document.documentElement as any).msRequestFullscreen) {
            cc.log(`${cc.js.getClassName(this)} msRequestFullscreen`);

            (document.documentElement as any).msRequestFullscreen()
        } else if ((document.documentElement as any).oRequestFullscreen) {
            cc.log(`${cc.js.getClassName(this)} oRequestFullscreen`);

            (document.documentElement as any).oRequestFullscreen()
        } else if ((document.documentElement as any).webkitRequestFullscreen) {
            cc.log(`${cc.js.getClassName(this)} webkitRequestFullscreen`);

            (document.documentElement as any).webkitRequestFullscreen()
        } else {
            cc.log(`${cc.js.getClassName(this)} otherFullscreen`);

            // 手写css布局 暂无
            (document as any).IsFullScreen = true
        }
    }

    /**
     * 浏览器退出全屏
     */
    _exitFullscreen() {
        cc.log(`${cc.js.getClassName(this)} _exitFullscreen`)

        if (document.exitFullscreen) {
            cc.log(`${cc.js.getClassName(this)} exitFullscreen`)

            document.exitFullscreen()
        } else if ((document as any).msExitFullscreen) {
            cc.log(`${cc.js.getClassName(this)} msExitFullscreen`);

            (document as any).msExitFullscreen()
        } else if ((document as any).mozCancelFullScreen) {
            cc.log(`${cc.js.getClassName(this)} mozCancelFullScreen`);

            (document as any).mozCancelFullScreen()
        } else if ((document as any).oRequestFullscreen) {
            cc.log(`${cc.js.getClassName(this)} oRequestFullscreen`);

            (document as any).oCancelFullscreen()
        } else if ((document as any).webkitExitFullscreen) {
            cc.log(`${cc.js.getClassName(this)} webkitExitFullscreen`);

            (document as any).webkitExitFullscreen()
        } else {
            cc.log(`${cc.js.getClassName(this)} otherExitFullscreen`);

            // 手写css布局 暂无
            (document as any).IsFullScreen = false
        }
    }

    /**
     * 锁定浏览器屏幕方向
     */
    _lockOrientation() {
        cc.log(`${cc.js.getClassName(this)} _lockOrientation`)

        let type: OrientationLockType = this._direction === `V` ? `portrait-primary` : `landscape-primary`
        if ((screen as any).mozLockOrientation) {
            (screen as any).mozLockOrientation(type)
        } else {
            screen.orientation.lock(type)
        }
    }

    // ====================================================================================
    // ===================================== 外部接口 ======================================
    // ====================================================================================

    /**
     * 旋转屏幕（暂时只支持正竖屏和横屏切换）
     * @return 执行后是否竖屏
     */
    rotateScreen() {
        cc.log(`${cc.js.getClassName(this)} rotateScreen`)

        this._direction = this._direction === `V` ? `H` : `V`

        // 执行原生旋转
        if (cc.sys.isMobile) {
            if (cc.sys.isBrowser) {
                if (this._direction === `V`) {
                    this._lockOrientation()
                    this._exitFullscreen()
                } else {
                    this._requestFullscreen()
                    this._lockOrientation()
                }
            } else if (cc.sys.isNative) {
                cc.sys.os === cc.sys.OS_ANDROID && jsb.reflection.callStaticMethod(`org/core/AndroidBridge`, `setOrientation`, `(Ljava/lang/String;)V`, this._direction)
                cc.sys.os === cc.sys.OS_IOS && jsb.reflection.callStaticMethod(`AppleBridge`, `setOrientation:`, this._direction)
            }
        }

        let frameSize = cc.view.getFrameSize()
        console.log(`frameSize: ` + frameSize.width + `   ` + frameSize.height)

        // 同步修改cocos配置
        if (this._direction === `V`) {
            cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT)
            frameSize.width > frameSize.height && cc.view.setFrameSize(frameSize.height, frameSize.width)
            this._canvas.designResolution = cc.size(this._designResolution.width, this._designResolution.height)
            this._canvas.fitWidth = true
            this._canvas.fitHeight = false
        } else {
            cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE)
            frameSize.height > frameSize.width && cc.view.setFrameSize(frameSize.height, frameSize.width)
            this._canvas.designResolution = cc.size(this._designResolution.height, this._designResolution.width)
            this._canvas.fitWidth = false
            this._canvas.fitHeight = true
        }

        //手动调用触发 Wdiget 组件重新布局
        if (!cc.sys.isBrowser) {
            dispatchEvent(new cc.Event.EventCustom(`resize`, true) as any)
        } else {
            cc.view.emit(`canvas-resize`)
        }
        let wdgts = this._canvas.node.getComponentsInChildren(cc.Widget)
        wdgts.forEach(wdgt => {
            wdgt.updateAlignment()
        })

        return this._direction === `V`
    }

    /**
     * 是否竖屏
     */
    isPortait() {
        // cc.log(`${cc.js.getClassName(this)} isPortait ` + (this._direction === `V`))

        return this._direction === `V`
    }

    /**
     * 绑定浏览器退出全屏回调
     * @param call 回调
     */
    bindEventExitFullScreen(call) {
        cc.log(`${cc.js.getClassName(this)} bindEventExitFullScreen`)

        window.onresize = () => {
            let isFull = document.fullscreenEnabled || (window as any).fullScreen || (document as any).webkitIsFullScreen || (document as any).msFullscreenEnabled
            if (!isFull) {
                call && call()
            }
        }
    }
}